
package com.scs.application.modules.settlement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.export.ExportParamDto;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.design.service.QueryGenerator;
import com.scs.application.modules.settlement.entity.DeptOprtUseItem;
import com.scs.application.modules.settlement.mapper.DeptOprtUseItemMapper;
import com.scs.application.modules.settlement.request.DeptOprtUseItemQueryRequest;
import com.scs.application.modules.settlement.service.DeptOprtUseItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 病人消耗子表 service 实现
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DeptOprtUseItemServiceImpl extends BaseServiceImpl<DeptOprtUseItemMapper, DeptOprtUseItem> implements DeptOprtUseItemService {

    @Override
    public List<DeptOprtUseItem> list(DeptOprtUseItemQueryRequest request) {
        List<DeptOprtUseItem> list = this.list(getQueryWrapper(request));
        return list;
    }

    @Override
    public IPage<DeptOprtUseItem> page(DeptOprtUseItemQueryRequest request) {
        IPage page = this.page(request.getPage(), getQueryWrapper(request));
        return page;
    }

    private QueryWrapper<DeptOprtUseItem> getQueryWrapper(DeptOprtUseItemQueryRequest request) {
        return Wrappers.<DeptOprtUseItem>query()
                .eq("dept_oprt_use_id", request.getDeptOprtUseId())
                .eq("supplier_id", UserUtils.getSupplierId())
                .orderByDesc("gmt_modified");
    }


    @Override
    public String exportFullData(QueryWrapper queryWrapper, ExportParamDto exportParams, Map<String, Object> userParam, HttpServletRequest request) {
        List result = null;
        if (exportParams.getIsAll()) {
            result = baseMapper.pageSumList(queryWrapper);
        } else{
            IPage  page = QueryGenerator.parsePage(request);
            result = baseMapper.pageSumDtl(page,queryWrapper).getRecords();
        }

        try {
            String downloadPath = exportService.export(result, exportParams);
            return downloadPath;
        } catch (Exception e) {
            log.error("BaseServiceImpl.exportFullData", e);
            throw new BusinessException("文件生成失败，原因：" + e != null ? e.getMessage() : "未知异常");
        }
    }
}
